<?php
namespace app\common\service;
class Trade{
	var $diancha;
	var $shouxufei;
	public function __construct(){
		// $setinfo = ev_setting();
		$this->diancha = 0;//$setinfo['diancha']; //点差
		$this->shouxufei = 0;//$setinfo['jiaoyi']; //交易手续费
		$this->saleprice = 0;//$setinfo['saleprice']; //出金手续费
		$this->buyprice = 0;//$setinfo['buyprice']; //入金手续费
	}
	/**
	 * 冻结资金计算
	 * @param  [float] $price [卖价或买价]
	 * @param  [int] $nums  [买卖数量]
	 * @param  [int] $typeid  [typeid = 1买入，typeid = 2卖出]
	 * @return [float]        [冻结资金]
	 */
	public function frost_amount($price,$nums,$typeid = 1,$userid = 0){
		$diancha = $this->diancha / 2;
		$amount = 0.00;
		if($typeid == 1){ //买
			$amount = $nums * $price + $this->total_frost($price,$nums,$userid);
			// $amount = $nums * ($price + $diancha) + $nums * $price * $this->shouxufei * get_user_sxf_youhui($userid);
		}
		else if($typeid == 2){
			$amount = $nums * $price - $this->total_frost($price,$nums,$userid);
			// $amount = $nums * ($price - $diancha) - $nums * $price * $this->shouxufei * get_user_sxf_youhui($userid);
		}
		return $amount;
	}
	/**
	 * 手续费总和计算
	 * @param  [float]  $price  [交易价格]
	 * @param  [interger]  $nums   [交易数量]
	 * @param  integer $userid [交易用户]
	 * @return [float]          [手续费总和]
	 */
	public function total_frost($price,$nums,$userid = 0){
		$diancha = $this->diancha / 2;
		$amount = $nums * $diancha + $nums * $price * $this->shouxufei * 1;//get_user_sxf_youhui($userid);
		return $amount;
	}
	/**
	 * 手续费计算
	 * @param  [float] $price [卖价或买价]
	 * @param  [int] $nums  [买卖数量]
	 * @param  [int] $typeid  [typeid = 1买入，typeid = 2卖出]
	 * @return [float]        [手续费金额]
	 */
	public function sxf_amount($price,$nums,$typeid = 1,$userid = 0){
		$amount = 0.00;
		if($typeid == 1){ //买
			$amount = $nums * $price * $this->shouxufei * 1;//get_user_sxf_youhui($userid);
		}
		else if($typeid == 2){
			$amount = $nums * $price * $this->shouxufei * 1;//get_user_sxf_youhui($userid);
		}
		return $amount;
	}
	/**
	 * 获取成交价格，谁买卖的早，已谁的价格为主
	 * @param  [int] $time1  [时间1] 对应价格1
	 * @param  [int] $time2  [时间2] 对应价格2
	 * @param  [float] $price1 [价格1]
	 * @param  [float] $price2 [价格2]
	 * @return [float]         [价格]
	 */
	public function get_price($time1,$time2,$price1,$price2){
		if($time1 >= $time2){
			$price = $price2;
		}
		else{
			$price = $price1;
		}
		return $price;
	}
	public function match_trade($orderid){
		$info = model("VirtualOrder")->where("id = '$orderid' and status = 0")->find();
		if(empty($info)) return false;
		switch ($info['typeid']) {
			case 1:
				$lastnums = $this->buy_match($info);
				break;
			case 2:
				$lastnums = $this->sale_match($info);
				break;
			default:
				$lastnums = false;
				break;
		}
		return $lastnums;
	}
	public function buy_match($orderInfo){
		$price = $orderInfo['price'];
		$nums = $orderInfo['surnums'];
		$cityid = $orderInfo['cityid'];
		$list = db("VirtualOrder")->where("price <= $price and status = 0 and typeid = 2 and cityid = '$cityid'")->order("price asc,id asc")->field("addtime,nums,id,surnums,price,userid")->select();
		foreach($list as $vorderInfo){
			$lastnums = $nums - $vorderInfo['surnums'];
			$cjprice = $this->get_price($orderInfo['addtime'],$vorderInfo['addtime'],$orderInfo['price'],$vorderInfo['price']);
			$isok = 0;
			if($lastnums > 0){ //买方还有剩余
				$cjnums = $vorderInfo['surnums'];
				//把当前卖的平仓
				$this->close_order($vorderInfo['id'],0,$cjnums,$cjprice);
				//把买的部分平仓
				$this->close_order($orderInfo['id'],$lastnums,$cjnums,$cjprice);

				

				$nums = $lastnums;
			}
			else if($lastnums < 0){ //卖方还有剩余
				$cjnums = $nums;
				//把当前买的平仓
				$this->close_order($orderInfo['id'],0,$cjnums,$cjprice);
				//把卖的部分平仓
				$this->close_order($vorderInfo['id'],$vorderInfo['surnums'] - $cjnums,$cjnums,$cjprice);

				$isok = 1;
			}
			else{
				$cjnums = $nums;
				//把当前买的平仓
				$this->close_order($orderInfo['id'],0,$cjnums,$cjprice);
				//把卖的平仓
				$this->close_order($vorderInfo['id'],0,$cjnums,$cjprice);

				

				$isok = 1;
			}
			$this->set_realtime($cjprice,1);
			model("VorderLog")->add_log($orderInfo['userid'],$vorderInfo['userid'],$cjprice,$cjnums,$orderInfo['id'],$vorderInfo['id'],$cityid);
			//记录买入日志
			model("VpointLog")->add_point($orderInfo['userid'],$cjprice,$cjnums,$cityid); //买入
			model("VpointLog")->set_point_price($vorderInfo['userid'],$cjprice,$cjnums,$cityid); //卖出处理，$userid,$nums,$price

			if($isok) break;
		}
		return $lastnums;
	}
	public function sale_match($orderInfo){
		$price = $orderInfo['price'];
		$nums = $orderInfo['surnums'];
		$cityid = $orderInfo['cityid'];
		$list = db("VirtualOrder")->where("price >= $price and status = 0 and typeid = 1 and cityid = '$cityid'")->order("price desc,id asc")->field("addtime,nums,surnums,id,price,userid")->select();
		$salenums = 0;
		foreach($list as $vorderInfo){
			$lastnums = $nums - $vorderInfo['surnums'];
			$cjprice = $this->get_price($orderInfo['addtime'],$vorderInfo['addtime'],$orderInfo['price'],$vorderInfo['price']);
			$isok = 0;
			if($lastnums > 0){ //卖还有剩余
				$cjnums = $vorderInfo['surnums'];

				//把当前买的平仓
				$this->close_order($vorderInfo['id'],0,$cjnums,$cjprice);
				//把卖的部分平仓
				$this->close_order($orderInfo['id'],$lastnums,$cjnums,$cjprice);


				$nums = $lastnums;
			}
			else if($lastnums < 0){ //买方还有剩余
				$cjnums = $nums;
				//把当前卖的平仓
				$this->close_order($orderInfo['id'],0,$cjnums,$cjprice);
				//把买的部分平仓
				$this->close_order($vorderInfo['id'],$vorderInfo['surnums'] - $cjnums,$cjnums,$cjprice);
				$isok = 1;
			}
			else{
				$cjnums = $nums;

				//把当前卖的平仓
				$this->close_order($orderInfo['id'],0,$cjnums,$cjprice);
				//把买的平仓
				$this->close_order($vorderInfo['id'],0,$cjnums,$cjprice);
				
				$isok = 1;
			}
			$salenums += $cjnums;
			$this->set_realtime($cjprice,2);
			model("VorderLog")->add_log($vorderInfo['userid'],$orderInfo['userid'],$cjprice,$cjnums,$vorderInfo['id'],$orderInfo['id'],$cityid);
			//记录买入日志
			model("VpointLog")->add_point($vorderInfo['userid'],$cjprice,$cjnums,$cityid); //买入

			// $this->set_sxf_tc($price,$cjnums,$userid,$orderid = 0);
			if($isok) break;
		}
		if($salenums)
			model("VpointLog")->set_point_price($orderInfo['userid'],$cjprice,$salenums,$cityid); //卖出处理，$userid,$nums,$price
		return $lastnums;
	}
	/**
	 * 设置最新价
	 * @param [float]  $price  [最新成交价] 
	 * @param integer $typeid [交易类型1=买入，2=卖出]
	 */
	public function set_realtime($price,$cityid,$typeid = 1){
		$priceData = array(
			'newprice' => $price,
		);
		if($typeid == 1){
			$priceData['buyprice'] = $price;
		}
		else if($typeid == 2){
			$priceData['saleprice'] = $price;
		}
		db("CityHaoling")->where("cityid = '$cityid'")->update($priceData);

		//设置价格触发
		// exec("/usr/local/php-5.6/bin/php -c /home/wwwroot/web/etc/amh-php.ini /home/wwwroot/web/domain/yuanliu/web/cli.php cron/enable_ev/price/".$price." > /dev/null &");
	}
	// public function set_sxf_tc($price,$cjnums,$userid,$orderid = 0){
	// 	$sxf = $this->sxf_amount($price,$cjnums,1,$userid);
	// 	//计算手续费提成
	// 	$setting = F("setting");
	// 	$ev_agent_sxf_tc = round($sxf * ($setting['ev_agent_sxf_tc'] / 100) * 100) / 100;
	// 	$tc_userid = get_agent_user($userid);
	// 	D("MemberPoint")->where("userid='$tc_userid'")->setInc('vamount',$ev_agent_sxf_tc);

	// 	//加入日志
	// 	//public function addLog($userid,$childid,$price,$orderid,$nums){
	// 	//$userid,$childid,$price,$typeid = 1,$orderid = 0,$nums = 0
	// 	D("AgentProfitLog")->addLog($tc_userid,$userid,$ev_agent_sxf_tc,2,$orderid,$cjnums);
	// }
	/**
	 * 平仓操作
	 * @param  [intger]  $orderid [平仓的订单号]
	 * @param  integer $nums    [平仓后剩余数量，0代表全部平仓，正数代表还有剩余，是部分平仓]
	 * @param  interger $cjnums [本地成交的数量]
	 * @return [boolen]           [是否执行成功]
	 */
	public function close_order($orderid,$nums = 0,$cjnums = 0,$price = 0){
		$orderData['surnums'] = $nums;
		if(!$nums){
			$orderData['status'] = 1;
			db("OrderQueue")->where("orderid = '$orderid'")->delete(); //如果被平仓，将此订单相关信息从对列出移除
		}
		$userid = db("VirtualOrder")->where("id = '$orderid'")->value("userid");
		model("Message")->add_msg($userid,"号令交易成功");
		model("Dynamic")->add_msg($userid,"号令交易成功");

		model("MemberGroup")->upgrade($userid);
		// $orderinfo = M("VirtualOrder")->where("id = '$orderid'")->field("price,typeid,userid")->find();
		// $typeid = $orderinfo['typeid'];
		// if($typeid == 1){
			// $price = $orderinfo['price'];
		// $sxf = $this->sxf_amount($price,$cjnums,1,$orderinfo['userid']);
		// //计算手续费提成
		// $setting = F("setting");
		// $ev_agent_sxf_tc = round($sxf * ($setting['ev_agent_sxf_tc'] / 100) * 100) / 100;
		// $tc_userid = get_agent_user($orderinfo['userid']);
		// D("MemberPoint")->where("userid='$tc_userid'")->setInc('vamount',$ev_agent_sxf_tc);

		// D("Stat")->add_stat(35,$tc_userid,$ev_agent_sxf_tc); //手续费提成
		// D("Stat")->add_stat(37,$tc_userid,$ev_agent_sxf_tc); //增加余额
		// //加入日志
		// //public function addLog($userid,$childid,$price,$orderid,$nums){
		// //$userid,$childid,$price,$typeid = 1,$orderid = 0,$nums = 0
		// D("AgentProfitLog")->addLog($tc_userid,$orderinfo['userid'],$ev_agent_sxf_tc,2,$orderid,$cjnums);
		// }
		// else if($typeid == 2){
		// 	// $price = $orderinfo['price'];
		// 	$sxf = $this->sxf_amount($price,$cjnums,2,$orderinfo['userid']);
		// 	//计算手续费提成
		// 	$setting = F("setting");
		// 	$ev_agent_sxf_tc = round($sxf * ($setting['ev_agent_sxf_tc'] / 100) * 100) / 100;
		// 	$tc_userid = get_agent_user($orderinfo['userid']);
		// 	D("MemberPoint")->where("userid='$tc_userid'")->setInc('evpoint',$ev_agent_sxf_tc);

		// 	//加入日志
		// 	//public function addLog($userid,$childid,$price,$orderid,$nums){
		// 	D("AgentProfitLog")->addLog($tc_userid,$orderinfo['userid'],$ev_agent_sxf_tc,2,$orderid,$cjnums);
		// }
		// $userid = $orderinfo['userid'];
		// M("Member")->where("userid = '$userid'")->setInc("trades");
		// D("EcTuijian")->set_member_valid($userid);
		return db("VirtualOrder")->where("id = '$orderid'")->update($orderData);
	}
	public function cancel_order($orderid){
		$orderinfo = db("VirtualOrder")->where("id = '$orderid'")->find();
		if($orderinfo['status'] != 0) return false;
		$surnums = $orderinfo['surnums'];
		$userid = $orderinfo['userid'];
		//将订单标记为撤单状态
		db("VirtualOrder")->where("id = '$orderid'")->setField("status",-1);
		//删除队列
		db("OrderQueue")->where("orderid = '$orderid'")->delete();
		if($orderinfo['typeid'] == 1){ //如果是买
			//退回相对应的冻结资金
			$dj_amount = $this->frost_amount($orderinfo['price'],$surnums,1,$userid);

			// if($orderinfo['buytype'] == 1){ //仅使用余额
				db("Member")->where("id = '$userid'")->setDec("dis_amount",$dj_amount); //减少冻结资金
				model("MemberAmountLog")->add($userid,1,7,$dj_amount,"买入撤单解冻金额");
				// db("Member")->where("id = '$userid'")->setInc("amount",$dj_amount); //增加金额

				// D("Stat")->add_stat(24,$userid,$dj_amount); //解冻金额
			// }
			// else if($orderinfo['buytype']){ //如果有使用积分的，全部退给积分
			// 	M("MemberPoint")->where("userid='$userid'")->setDec('evpoint_dj',$dj_amount); //减少交易冻结
			// 	M("MemberPoint")->where("userid='$userid'")->setInc('evpoint',$dj_amount); //增加可用积分

			// 	D("Stat")->add_stat(25,$userid,$dj_amount); //解冻积分
			// }

			// M("MemberPoint")->where("userid = '$userid'")->setDec("dis_vamount",$dj_amount); //减少冻结资金
			// M("MemberPoint")->where("userid = '$userid'")->setInc("vamount",$dj_amount); //增加金额
		}
		else if($orderinfo['typeid'] == 2){//如果是卖
			$cityid = $orderinfo['cityid'];
			//退回冻结的权益值
			db("MemberHaoling")->where("userid = '$userid' and cityid = '$cityid'")->setInc("nums",$surnums);
			db("MemberHaoling")->where("userid = '$userid' and cityid = '$cityid'")->setDec("dis_nums",$surnums);

			// D("Stat")->add_stat(31,$userid,$surnums); //解冻权益值
		}
		return true;
	}
}